package com.snow.useviewdemo.function.surface;


import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.bean.InfoCode;
import com.aliyun.player.source.UrlSource;
import com.snow.common.tool.utils.ToastUtils;

/**
 * author : zyt
 * e-mail : 632105276@qq.com
 * date   : 2019/3/6
 * desc   :
 */

public class LivePlayerManager {
    private AliPlayer aliyunVodPlayer;
    private Context mContext;
    private int voiceValue = 20;
    private LPMProgressListener progressListener;
    //是否需要重新打开音量，音量大小是关闭之前的
    private boolean isNeedReOpenVolume;
    private int currentPlayState;//当前播放状态
    private long currentPlayPosition;//当前播放进度

    public LivePlayerManager(Context mContext) {
        this.mContext = mContext;
        aliyunVodPlayer = AliPlayerFactory.createAliPlayer(mContext);
        //循环播放
//        aliyunVodPlayer.setOnCircleStartListener(new MyCircleStartListener(this));
        //准备播放监听
        aliyunVodPlayer.setOnPreparedListener(() -> {
            aliyunVodPlayer.start();
            if (progressListener != null) {
                progressListener.playPrepared();
                handler.sendEmptyMessage(1111);
            }
            if (lpmPlayListener != null) {
                lpmPlayListener.playPrepared();
            }
        });
        //第一帧画面展示
        aliyunVodPlayer.setOnRenderingStartListener(() -> {

        });
        //播放错误
        aliyunVodPlayer.setOnErrorListener(arg0 -> {
            //出错时处理，查看接口文档中的错误码和错误消息
        });
        //播放完成监听
        aliyunVodPlayer.setOnCompletionListener(() -> {
            if (lpmPlayListener != null) {
                lpmPlayListener.playComplete();
            }
        });
        aliyunVodPlayer.setOnSeekCompleteListener(() -> {
            //seek完成时触发
        });
        aliyunVodPlayer.setOnStateChangedListener(newState -> {
            //播放器状态改变事件
//            int prepared = 2;
//            int started = 3;
//            int paused = 4;
//            int stopped = 5;
            currentPlayState = newState;
        });
        /**
         * 获取播放信息===进度
         */
        aliyunVodPlayer.setOnInfoListener(infoBean -> {
            if (infoBean.getCode() == InfoCode.CurrentPosition) {//获取播放进度
                currentPlayPosition = infoBean.getExtraValue();
            }
        });
        //设置画面缩放模式：宽高比填充，宽高比适应，拉伸填充
        aliyunVodPlayer.setScaleMode(IPlayer.ScaleMode.SCALE_ASPECT_FIT);

    }

    public AliPlayer getaliyunVodPlayer() {
        if (aliyunVodPlayer == null) {
            aliyunVodPlayer = AliPlayerFactory.createAliPlayer(mContext);

        }
        return aliyunVodPlayer;
    }

    /**
     * 设置播放源
     *
     * @param playPath 播放源
     */
    public void setPlaySource(String playPath) {
        if (TextUtils.isEmpty(playPath)) {
            ToastUtils.getInstance().showToast("播放链接不能为空！");
            return;
        }
        UrlSource urlSource = new UrlSource();
//        asb.setSource("http://player.alicdn.com/video/aliyunmedia.mp4");
        urlSource.setUri(playPath);
        aliyunVodPlayer.setDataSource(urlSource);
        aliyunVodPlayer.prepare();
//        AliyunLocalSource.AliyunLocalSourceBuilder localSource = new AliyunLocalSource.AliyunLocalSourceBuilder();
//        localSource.setSource(playPath);
//        setPlaySource(localSource.build());
    }

    /**
     * 关闭声音
     */
    public void closeVolume() {
        voiceValue = (int) aliyunVodPlayer.getVolume();
        isNeedReOpenVolume = true;
        aliyunVodPlayer.setVolume(0);
    }

    /**
     * 打开声音
     */
    public void reOpenVolume() {
        if (voiceValue > 0 && isNeedReOpenVolume) {
            aliyunVodPlayer.setVolume(voiceValue);
            isNeedReOpenVolume = false;
        }
    }

    /**
     * 设置播放声音
     *
     * @param voiceValue
     */
    public void setVoiceValue(int voiceValue) {
        this.voiceValue = voiceValue;
        if (aliyunVodPlayer == null) {
            return;
        }
        aliyunVodPlayer.setVolume(voiceValue);
    }

    public void stop() {
        handler.removeMessages(1111);
        if (aliyunVodPlayer == null) {
            return;
        }
        aliyunVodPlayer.stop();
        aliyunVodPlayer.reset();
    }

    public void pause() {
        handler.removeMessages(1111);
        if (aliyunVodPlayer == null) {
            return;
        }
        aliyunVodPlayer.pause();
    }

    public void resume() {
        handler.sendEmptyMessage(1111);
        if (aliyunVodPlayer == null) {
            return;
        }
        aliyunVodPlayer.start();
    }

    private int progressInt = 0;
    private long lastCurrentPosition;
    //播放进度监听
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1111:
                    if (progressListener != null) {
                        if (lastCurrentPosition != currentPlayPosition) {
                            lastCurrentPosition = currentPlayPosition;
                            progressInt++;
                            progressListener.playProgress(progressInt);
                        }
                    }
                    handler.sendEmptyMessageDelayed(1111, 1000);
                    break;
            }
            return false;
        }
    });

    /**
     * 播放状态监听
     *
     * @param lpmPlayListener
     */
    public void setPlayStateListener(LPMPlayListener lpmPlayListener) {
        this.lpmPlayListener = lpmPlayListener;
    }

    private LPMPlayListener lpmPlayListener;

    public interface LPMPlayListener {
        void playPrepared();

        void playComplete();
    }

    /**
     * 播放进度监听
     *
     * @param progressListener
     */
    public void setProgressListener(LPMProgressListener progressListener) {
        this.progressListener = progressListener;
    }

    public interface LPMProgressListener {
        void playPrepared();

        void playProgress(int progress);
    }
}
